import * as $dd from '@ali/dingtalk-jsapi'; // 此方式为整体加载，也可按需进行加载
import axios from "axios";

// 改成lwp方式不要签名，有此方式免登
async function ddlwp(corpId) {
  return new Promise((resolve, reject) => {
    try {
      let obj = {
        success: false,
        errorMsg: "",
        result: []
      }
      if (!corpId) {
        obj.errorMsg = "请输入corpId";
        resolve(obj);
        return;
      }
      if (corpId == "$CORPID$") {
        obj.errorMsg = "corpId错误，请确定参数";
        resolve(obj);
        return;
      }
      $dd.biz.user.get({
        corpId: corpId,
      }).then((getRes) => {
        console.log('getRes', getRes)
        $dd.internal.request.lwp({
          uri: '/r/Adaptor/YunqiI/getLWPLoginUserInfo',
          body: [],
          onSuccess: (lwpRes) => {
            console.log('lwp', lwpRes);
            if (!lwpRes.body) {
              obj.errorMsg = "钉钉lwp接口环境异常，用户信息获取失败";
              resolve(obj);
              return;
            }
            if (lwpRes.body.success) {
              let authUrl = `/api/isv/loginUser/getLoginUser?token=${lwpRes.body.result}&corpId=${corpId}&userId=${getRes.emplId}`;
              axios.get(authUrl).then(axiosRes => {
                if (axiosRes.data.success) {
                  axios.defaults.headers.common['Authorization'] = axiosRes.data.result.token; //请求头文件
                  obj.success = true;
                  obj.result = axiosRes.data.result;
                  resolve(obj);
                } else {
                  obj.errorMsg = axiosRes.data.errorMsg || `用户信息获取失败`;
                  resolve(obj);
                  return;
                }
              }, err => {
                obj.errorMsg = `获取用户信息失败`;
                resolve(obj);
                return;
              });
            } else {
              obj.errorMsg = lwpRes.body.reason || `用户信息获取失败`;
              resolve(obj);
              return;
            }
          },
          onFail: (err) => {
            obj.errorMsg = "钉钉lwp接口异常，用户信息获取失败";
            resolve(obj);
            return;
          },
        });
      }, err => {
        obj.errorMsg = "钉钉get接口异常，用户信息获取失败";
        resolve(obj);
        return;
      })
    } catch (error) {
      reject(error);
    }
  });
}


export {
  ddlwp
}
